/**
 *
 */
package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.socket.SocketInputThread;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.CustomOneBtnDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.droidparts.widget.ClearableEditText;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.Callable;
import java.util.zip.CRC32;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import bolts.Continuation;
import bolts.Task;

//import static com.jdy.zhdd.R.id.gray_layout;
//import static com.jdy.zhdd.R.id.progress_in;

/**
 * @author zp 2016-4-21 下午3:08:36
 */
public class ConnectWifiActivity extends BaseActivity implements
        OnClickListener {

  @InjectView(id = R.id.input_password)
  private ClearableEditText input_password;
  @InjectView(id = R.id.input_wifiname)
  private ClearableEditText input_wifiname;
  @InjectView(id = R.id.synchronize_wifi_btn, click = true)
  private Button mSyncWifiBtn;
//  @InjectView(id = R.id.progress_in)
//  private ProgressBar progress_in;

  private int mLocalIp;
  private String mSSID;
  private Thread mThread = null;
  private boolean mDone = false;

  void updateWifiInfo() {
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (!networkInfo.isConnected()) {
      showErrorDialog();
      return;
    }

    wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiInf = wifiMgr.getConnectionInfo();

    mLocalIp = wifiInf.getIpAddress();
    mSSID = wifiInf.getSSID();
    if (Tools.isNotEmpty(mSSID) && mSSID.startsWith("\"")) {
      mSSID = mSSID.substring(1, mSSID.length() - 1);
    }

    input_wifiname.setText(mSSID);
    if (Tools.isNotEmpty(input_wifiname.getText().toString())) {
      input_password.requestFocus();
    }
  }


  private void resetBindTime() {

    new CustomAsyncTask(this, new IAsyncTask() {

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
                +  "/api/2.0/member/bind/reset_bind_time", param_, HttpUtils.TAG_POST_REQUEST);
      }

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
           if (result.isSuccess()) {
             // TODO
           }
      }
    }).execute();
  }

  @Override
  protected void onDestroy() {
    if (mCustomCommonDialog != null) {
      mCustomCommonDialog.dismiss();
      mCustomCommonDialog = null;
    }

    if (dlgOverTime != null) {
      dlgOverTime.dismiss();
      dlgOverTime = null;
    }

    if (mhandler != null) {
      mhandler.removeCallbacksAndMessages(null);
      mhandler = null;
    }

    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }

    if (xmitStarted) {
      xmitStarted = false;
      if (xmitter != null && !xmitter.isCancelled()) {
        xmitter.cancel(true);
      }
    }

    if (mhandler2 != null) {
      mhandler2.removeCallbacksAndMessages(null);
      mhandler2 = null;
    }

    if (mediaPlayer != null) {
      mediaPlayer.stop();
      mediaPlayer.release();
      mediaPlayer = null;
    }

    super.onDestroy();
  }

  void showErrorDialog() {
    CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(ConnectWifiActivity.this)
            .setMessage("WiFi没有连接，请确保手机连上WiFi")
            .setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // showTipDialog();
                      }
                    });

    CustomOneBtnDialog dddd = cdb.create();
    if (!isFinishing()) {
      dddd.show();
    }

//    AlertDialog.Builder builder = new AlertDialog.Builder(this);
//    builder.setMessage(R.string.connect_wifi);
//    builder.setPositiveButton(android.R.string.ok,
//        new DialogInterface.OnClickListener() {
//          @Override
//          public void onClick(DialogInterface dialog, int whichButton) {
//            finish();
//          }
//        });
//    builder.create().show();
  }

  private String fromPage;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect_wifi_layout);
    setTitle("设置Wi-Fi绑定");

    getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    //mTvUpright.setVisibility(View.VISIBLE);
   // mTvUpright.setText("设置高配版");


    if (getIntent() != null) {
      fromPage = getIntent().getStringExtra("fromPage");
    }

    input_password.setTransformationMethod(PasswordTransformationMethod
            .getInstance());
    mSyncWifiBtn.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    resetBindTime();
  }

  @Override
  protected void onResume() {
    super.onResume();
    updateWifiInfo();
  }

  @Override
  protected void onPause() {
    super.onPause();
  }

  CustomOneBtnDialog mCustomCommonDialog;

  private Handler mhandler = new Handler();

  private Handler mhandler2 = new Handler();

  private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      if (msg.what == 42) {
        Log.d("MRVL", "ADI ASync task exited");
        xmitStarted = false;
      } else if (msg.what == 43) {
        // TxtDebug.setText("Information sent " + msg.arg1 / 2 + " times.");
      }
      super.handleMessage(msg);
    }
  };

  private class xmitterTask extends AsyncTask<String, Void, String> {
    byte[] passphrase;
    byte[] customData;
    byte[] cipherData;
    String ssid;
    char[] mac;
    char[] preamble;
    int passLen;
    int ssidLen;
    int customDataLen;
    int cipherDataLen;
    int passCRC;
    int ssidCRC;
    int customDataCRC;
    Handler handler;

    private int state, substate;

    public void resetStateMachine() {
      state = 0;
      substate = 0;
    }

    private void xmitRaw(int u, int m, int l) {
      MulticastSocket ms;
      InetAddress sessAddr;
      DatagramPacket dp;

      byte[] data = new byte[2];
      data = "a".getBytes();

      u = u & 0x7f; /* multicast's uppermost byte has only 7 chr */

      try {
//				Log.d("MRVL", "239." + u + "." + m + "." + l);
        sessAddr = InetAddress
                .getByName("239." + u + "." + m + "." + l);
        ms = new MulticastSocket(1234);
        dp = new DatagramPacket(data, data.length, sessAddr, 5500);
        ms.send(dp);
        ms.close();
      } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
        Log.e("MRVL", "Exiting 5");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    private void xmitState0(int substate) {
      int i, j, k;

      // Frame-type for preamble is 0b11110<substate1><substate0>
      // i = <frame-type> | <substate> i.e. 0x78 | substate
      k = preamble[2 * substate];
      j = preamble[2 * substate + 1];
      i = substate | 0x78;

      xmitRaw(i, j, k);
    }

    private void xmitState1(int substate, int len) throws UnsupportedEncodingException {
      // Frame-type for SSID is 0b10<5 substate bits>
      // u = <frame-type> | <substate> i.e. 0x40 | substate
      if (substate == 0) {
        int u = 0x40;
        xmitRaw(u, ssidLen, ssidLen);
      } else if (substate == 1 || substate == 2) {
        int k = (int) (ssidCRC >> ((2 * (substate - 1) + 0) * 8)) & 0xff;
        int j = (int) (ssidCRC >> ((2 * (substate - 1) + 1) * 8)) & 0xff;
        int i = substate | 0x40;
        xmitRaw(i, j, k);
      } else {
        int u = 0x40 | substate;
        int l = (0xff & ssid.getBytes("iso-8859-1")[(2 * (substate - 3))]);
        int m;
        if (len == 2)
          m = (0xff & ssid.getBytes("iso-8859-1")[(2 * (substate - 3)) + 1]);
        else
          m = 0;
        xmitRaw(u, m, l);
      }
    }

    private void xmitState2(int substate, int len) {
      // Frame-type for Passphrase is 0b0<6 substate bits>
      // u = <frame-type> | <substate> i.e. 0x00 | substate
      if (substate == 0) {
        int u = 0x00;
        xmitRaw(u, passLen, passLen);
      } else if (substate == 1 || substate == 2) {
        int k = (int) (passCRC >> ((2 * (substate - 1) + 0) * 8)) & 0xff;
        int j = (int) (passCRC >> ((2 * (substate - 1) + 1) * 8)) & 0xff;
        int i = substate;
        xmitRaw(i, j, k);
      } else {
        int u = substate;
        int l = (0xff & passphrase[(2 * (substate - 3))]);
        int m;
        if (len == 2)
          m = (0xff & passphrase[(2 * (substate - 3)) + 1]);
        else
          m = 0;
        xmitRaw(u, m, l);
      }
    }

    private void xmitState3(int substate, int len) {
      if (substate == 0) {
        int u = 0x60;
        xmitRaw(u, customDataLen, customDataLen);
      } else if (substate == 1 || substate == 2) {
        int k = (int) (customDataCRC >> ((2 * (substate - 1) + 0) * 8)) & 0xff;
        int j = (int) (customDataCRC >> ((2 * (substate - 1) + 1) * 8)) & 0xff;
        int i = substate | 0x60;
        xmitRaw(i, j, k);
      } else {
        int u = 0x60 | substate;
        int l = (0xff & cipherData[(2 * (substate - 3))]);
        int m;
        if (len == 2)
          m = (0xff & cipherData[(2 * (substate - 3)) + 1]);
        else
          m = 0;
        xmitRaw(u, m, l);
      }
    }

    private void stateMachine() throws UnsupportedEncodingException {
      switch (state) {
        case 0:
          if (substate == 3) {
            state = 1;
            substate = 0;
          } else {
            xmitState0(substate);
            substate++;
          }
          break;
        case 1:
          xmitState1(substate, 2);
          substate++;
          if (ssidLen % 2 == 1) {
            if (substate * 2 == ssidLen + 5) {
              xmitState1(substate, 1);
              state = 2;
              substate = 0;
            }
          } else {
            if ((substate - 1) * 2 == (ssidLen + 4)) {
              state = 2;
              substate = 0;
            }
          }
          break;
        case 2:
          xmitState2(substate, 2);
          substate++;
          if (passLen % 2 == 1) {
            if (substate * 2 == passLen + 5) {
              xmitState2(substate, 1);
              state = 3;
              substate = 0;
            }
          } else {
            if ((substate - 1) * 2 == (passLen + 4)) {
              state = 3;
              substate = 0;
            }
          }
          break;
        case 3:
          xmitState3(substate, 2);
          substate++;
          if (cipherDataLen % 2 == 1) {
            if (substate * 2 == cipherDataLen + 5) {
              xmitState3(substate, 1);
              state = 0;
              substate = 0;
            }
          } else {
            if ((substate - 1) * 2 == cipherDataLen + 4) {
              state = 0;
              substate = 0;
            }
          }
          break;
        default:
          Log.e("MRVL", "I shouldn't be here");
      }
    }

    @SuppressLint("MissingPermission")
    protected String doInBackground(String... params) {
      WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
      WifiManager.MulticastLock mcastLock = wm.createMulticastLock("mcastlock");
      mcastLock.acquire();

      int i = 0;

      while (true) {
        if (state == 0 && substate == 0)
          i++;

        if (i % 5 == 0) {
          Message msg = handler.obtainMessage();
          msg.what = 43;
          msg.arg1 = i;
          handler.sendMessage(msg);
        }

				/* Stop trying after doing 50 iterations. Let user retry. */
        if (i >= 600)
          break;

        if (isCancelled())
          break;

        try {
          stateMachine();
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }

//				try {
//					Thread.sleep(10);
//				} catch (InterruptedException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
//					break;
//				}
      }

      mcastLock.release();

      if (i >= 50) {
        Message msg = handler.obtainMessage();
        msg.what = 42;
        handler.sendMessage(msg);
      }
      return null;
    }


    @Override
    protected void onPostExecute(String result) {
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
  }

  WifiManager wifiMgr;
  WifiInfo wifiInf;
  Boolean xmitStarted = false;
  xmitterTask xmitter;
  static HashMap<String, String> passhash = new HashMap<String, String>();

  private static boolean validate(String pass, String key) {

//    if ((pass.length() != 0) && (pass.length() < 8 || pass.length() > 63)) {
//    //  TxtDebug.setText("Invalid passphrase. Passphrase must be 8 to 63 characters long.");
//      return false;
//    }
    if (key.length() > 16 && key.length() < 8) {
      //  TxtDebug.setText("Invalid key. Key must be 8 to 16 characters long.");
      return false;
    }
    return true;
  }

  private static byte[] hexStringToByteArray(String s, int blockLen) {
    int len = s.length();
    byte[] data = new byte[blockLen];
    Arrays.fill(data, (byte)0);
    for (int i = 0; i < len; i += 2) {
      data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
    }
    //   Log.d("MRVL", data.toString());
    return data;
  }

  public static byte[] myEncryptPassphrase(String key, byte[] plainText, String ssid) {

    byte[] iv = new byte[16];
    for (int i = 0; i < 16; i++)
      iv[i] = 0;

    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    Cipher cipher;
    byte[] encrypted = null;
    try {
      int iterationCount = 4096;
      int keyLength = 256;
      //int saltLength = keyLength / 8;
      byte salt[] = ssid.getBytes("iso-8859-1");

      Log.d("MRVL", "key salt itercount " + key + " " + ssid + " " + iterationCount);
      KeySpec keySpec = new PBEKeySpec(key.toCharArray(), salt, iterationCount, keyLength);

      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

      byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
      SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");

      cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
      encrypted = cipher.doFinal(plainText);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (BadPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return encrypted;
  }

  public static byte[] myEncryptCustomData(String key, byte[] plainText, String ssid) {

    byte[] iv = new byte[16];
    for (int i = 0; i < 16; i++)
      iv[i] = 0;

    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    Cipher cipher;
    byte[] encrypted = null;
    try {
      int iterationCount = 4096;
      int keyLength = 256;
      //int saltLength = keyLength / 8;
      byte salt[] = ssid.getBytes("iso-8859-1");

      Log.d("MRVL", "key salt itercount " + key + " " + ssid + " " + iterationCount);
      KeySpec keySpec = new PBEKeySpec(key.toCharArray(), salt, iterationCount, keyLength);

      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

      byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
      SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");

      cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
      encrypted = cipher.doFinal(plainText);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (BadPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return encrypted;
  }

  /**
   * 每5秒请求一次接口，共5次。获取成功后，进入下一步用户信息填写操作，恢复正常流程；若失败，则提示重新进行Wi-Fi设置，重复上述流程。
   *
   */
  private  Runnable runnable = new Runnable(){
    @Override
    public void run() {
      checkIfBindSuccess();
    }
  };

  private void doPageRoute() {
    if (LeConfig.isLogin) {
      if (LeConfig.isDeviceBinded) {
        if (LeConfig.isInfoFilled) {

          Intent intent = new Intent(this, MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                  | Intent.FLAG_ACTIVITY_CLEAR_TOP
                  | Intent.FLAG_ACTIVITY_NEW_TASK);

          startActivity(intent);

          finish();
        } else {
          Intent t = new Intent(this, FillInfoPopupActivity.class);
          t.putExtra("fromPage", "BindDeviceActivity");
          startActivity(t);
          finish();
        }
      } else {
      }
    } else {
    }
  }

  private void checkMacActivation(final String macId) {
    LeMachine macInfo = LeXiaoXiaoBanApp.getInstance().getBaby();
    LeConfig.isInfoFilled = false;

    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (macInfo != null) {
      if (Tools.isNotEmpty(macInfo.name)) {
        LeConfig.isInfoFilled = true;

        if (Tools.isNotEmpty(macInfo.activate)
                && !macInfo.activate.toString().equals("null")) {
          LeConfig.isDeviceActivated = !macInfo.activate.is_expired;
          //  LeConfig.expiredAt = macInfo.activate.expired_at;
        }
      }
    }

    doPageRoute();

    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
  }

  private void showTipDialog() {
    CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(ConnectWifiActivity.this)
            .setTitle("联网提示")
            .setMessage("正在为小小金机器人设置WIFI，由于网络环境差异首次联网时间可能较长，请耐心等待30秒左右时间，注意收听设备发出的提示音：\n\n" +
                    "1、如听到“设备联网成功”，说明设备已经联网绑定成功；\n" +
                    "2、如听到“帐号密码不正确”，请确认帐号密码后点击重新设置\n")
            .showProgross(true)
            .setPositiveButton("重新设置",
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        dismissLoading();

                        if (mediaPlayer != null) {
                          mediaPlayer.stop();
                          mediaPlayer.release();
                          mediaPlayer = null;
                        }

                        if (handler != null) {
                          handler.removeCallbacksAndMessages(null);
                        }

                        if (dlgOverTime != null) {
                          dlgOverTime.dismiss();
                        }

                        if (xmitStarted) {
                          xmitStarted = false;
                          if (xmitter != null && !xmitter.isCancelled()) {
                            xmitter.cancel(true);
                          }
                        }
                        //////////////////
                      }
                    });

    mCustomCommonDialog = cdb.create();
    mCustomCommonDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
      @Override
      public void onDismiss(DialogInterface dialog) {
        ///////////////
        //errcount = 0;
        //   showTipDialog();
        if (xmitStarted) {
          xmitStarted = false;
          if (xmitter != null && !xmitter.isCancelled()) {
            xmitter.cancel(true);
          }
        }

        if (mediaPlayer != null) {
          mediaPlayer.stop();
          mediaPlayer.release();
          mediaPlayer = null;
        }

        //////////////////
      }
    });

    if (!isFinishing()) {
      mCustomCommonDialog.show();
    }

    // progress_in.setVisibility(View.VISIBLE);
  }

  private boolean funcWorking = false;


  private CustomOneBtnDialog dlgOverTime;

  private void showErrTipDialog() {

    if (mCustomCommonDialog != null) {
      mCustomCommonDialog.dismiss();
    }

    if (dlgOverTime != null) {
      dlgOverTime.dismiss();
      dlgOverTime = null;
    }

    CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(ConnectWifiActivity.this)
            .setMessage("WIFI设置超时，请重新再试！")
            .setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // showTipDialog();

                        ///////////////
                        //errcount = 0;
                        //   showTipDialog();
                        if (xmitStarted) {
                          xmitStarted = false;
                          if (xmitter != null && !xmitter.isCancelled()) {
                            xmitter.cancel(true);
                          }
                        }

                        if (mediaPlayer != null) {
                          mediaPlayer.stop();
                          mediaPlayer.release();
                          mediaPlayer = null;
                        }
                        //////////////////

                      }
                    });

    dlgOverTime = cdb.create();
    if (!isFinishing()) {
      dlgOverTime.show();
    }
  }

  private void initCommunicateWay() {
      SocketInputThread.kickOffline = true;
      LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
      if (lb != null) {
        String url = lb.ip;
        if (Tools.isNotNullStr(url)) {
          StringTokenizer tokens = new StringTokenizer(url, ":");
          LeConfig.g_ServerIP = tokens.nextToken();
          LeConfig.FILE_PORT = Integer.parseInt(tokens.nextToken());
//          SocketThreadManager sss = SocketThreadManager.getInstance();
          SocketThreadManager.releaseInstance();
          SocketThreadManager.getInstance().disconnectOldConnectNew();

          Log.e("bbbbbbbbbb", "2222222222222");

          SocketThreadManager.getInstance().requestDeviceDetails();
          SocketThreadManager.getInstance().requestConnectDevice();
        }
      }

  }


  //  每5秒请求一次接口，共5次。获取成功后，进入下一步用户信息填写操作，恢复正常流程；若失败，则提示重新进行Wi-Fi设置，重复上述流程。
  private void checkIfBindSuccess() {
    if (funcWorking) {
      return;
    }

    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (Tools.isNotNullStr(result.data)) {
            final LeMachine lm = JsonSerializer.getInstance().deserialize(result.data, LeMachine.class);
            if (lm.interval < 60) {  // 绑定成功
              LeConfig.isDeviceBinded = true;
              Log.e("kkkkkkkkkkkkkkkk", "fdsfdsfdsfds");

              if (Tools.isNotNullStr(lm.name)) {
                LeConfig.MAC_ID = lm.id;
                LeXiaoXiaoBanApp.getInstance().setBaby(lm);
                Tools.saveLeBaby(lm);

                initCommunicateWay();

                handler.postDelayed(new Runnable() {
                  @Override
                  public void run() {
                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                    if (lu != null) {
                      lu.machine = lm;
                      LeXiaoXiaoBanApp.getInstance().setUser(lu);
                      Tools.saveLeUser(lu);
                    }

                    dismissLoading();
                    checkMacActivation(LeConfig.MAC_ID);

                    SocketInputThread.kickOffline = false;
                    toastShow("设置Wi-Fi绑定成功");
                  }
                }, 500);
              } else {
                initCommunicateWay();
                LeXiaoXiaoBanApp.getInstance().setBaby(lm);
                LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                if (lu != null) {
                  lu.machine = lm;
                  LeXiaoXiaoBanApp.getInstance().setUser(lu);
                  Tools.saveLeUser(lu);
                }

                handler.postDelayed(new Runnable() {
                  @Override
                  public void run() {
                    Intent t = new Intent(ConnectWifiActivity.this, FillInfoPopupActivity.class);
                    t.putExtra("fromPage", "BindDeviceActivity");
                    startActivity(t);
                    dismissLoading();
                    SocketInputThread.kickOffline = false;
                    toastShow("设置Wi-Fi绑定成功");
                    finish();
                  }
                }, 500);
              }
            } else {
                if (mhandler != null) {
                  mhandler.removeCallbacksAndMessages(null);
                  mhandler.postDelayed(runnable, 5000);
                }
            }
          } else {
              if (mhandler != null) {
                mhandler.removeCallbacksAndMessages(null);
                mhandler.postDelayed(runnable, 5000);
              }
          }
        } else {
            if (mhandler != null) {
              mhandler.removeCallbacksAndMessages(null);
              mhandler.postDelayed(runnable, 5000);
            }
        }

        funcWorking = false;
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        funcWorking = true;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.HOST_API
                        + "/api/2.0/member/bind", param_,
                HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }
//
//  private void toWifiHotSpotListActivityHighVersion() {
//    String password = input_password.getText().toString();
//    if (Tools.isEmpty(password)) {
//      password = "";
//    }
//
//    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
//    if (lu == null) {
//      lu = Tools.restoreLeUser();
//    }
//
//    String mobile = lu.id;
//
//    final String psd = password;
//
//    if (!mDone) {
//      mDone = true;
//      /* set packet interval */
//      Cooee.SetPacketInterval(20); /* 10ms */
//
//      if (mThread == null) {
//        mThread = new Thread() {
//          @Override
//          public void run() {
//            while (mDone) {
//              // Cooee.send(ssid, password, mLocalIp, "0123456789abcdef");
//              Cooee.send(mSSID, psd + "!@&" + mobile, mLocalIp);
//              // Cooee.send(ssid, password);
//            }
//          }
//        };
//      }
//
//      mThread.start();
//    } else {
//      mDone = false;
//      mThread = null;
//    }
//  }


  private void toWifiHotSpotListActivity() {
    //   showloading("");

    String password = input_password.getText().toString();
    if (Tools.isEmpty(password)) {
      password = "";
    }

    final String pass = password;
    String key = "JDY0100020170602";
    String data = "";

    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu == null) {
      lu = Tools.restoreLeUser();
      if (lu != null) {
        data = lu.id + "0";
        int len = data.length();
        if(len%2 == 1){  // 奇数
          data += "0";
        }
      }
    } else {
      data = lu.id + "0";
      int len = data.length();
      if(len%2 == 1){  // 奇数
        data += "0";
      }
    }

    try {
      if (xmitStarted == false) {

        if (!validate(pass, key))
          return;
        xmitter = new xmitterTask();
        xmitter.handler = handler;

        xmitStarted = true;

        CRC32 crc32 = new CRC32();
        crc32.reset();
        crc32.update(pass.getBytes());
        xmitter.passCRC = (int) crc32.getValue() & 0xffffffff;


        if (wifiMgr == null) {
          wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        }

        String ssidName=wifiMgr.getConnectionInfo().getSSID();
        try {
          ssidName = new String(ssidName.getBytes("UTF-8"), "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }

        xmitter.ssid = ssidName;
        xmitter.ssidLen = ssidName.length();

        xmitter.customDataLen = data.length() / 2;
        if (xmitter.customDataLen % 16 == 0) {
          xmitter.cipherDataLen = xmitter.customDataLen;
        } else {
          xmitter.cipherDataLen = ((xmitter.customDataLen / 16) + 1) * 16;
        }
        xmitter.customData = hexStringToByteArray(data, xmitter.cipherDataLen);

        CRC32 crc32_customdata = new CRC32();
        crc32_customdata.reset();
        crc32_customdata.update(xmitter.customData);
        xmitter.customDataCRC = (int) crc32_customdata.getValue() & 0xffffffff;

        int deviceVersion = Build.VERSION.SDK_INT;

        if (deviceVersion >= 17) {
          if (xmitter.ssid.startsWith("\"") && xmitter.ssid.endsWith("\"")) {
            xmitter.ssidLen = ssidName.length() - 2;
            xmitter.ssid = xmitter.ssid.substring(1, xmitter.ssid.length() - 1);
          }
        }

        CRC32 crc32_ssid = new CRC32();
        crc32_ssid.reset();
        crc32_ssid.update(xmitter.ssid.getBytes("iso-8859-1"));
        xmitter.ssidCRC = (int) crc32_ssid.getValue() & 0xffffffff;

        if (key.length() != 0) {
          if (pass.length() % 16 == 0) {
            xmitter.passLen = pass.length();
          } else {
            xmitter.passLen = (16 - (pass.length() % 16))
                    + pass.length();
          }

          byte[] plainPass = new byte[xmitter.passLen];

          for (int i = 0; i < pass.length(); i++)
            plainPass[i] = pass.getBytes()[i];

          xmitter.passphrase = myEncryptPassphrase(key, plainPass, xmitter.ssid);
          xmitter.cipherData = myEncryptCustomData(key, xmitter.customData, xmitter.ssid);
        } else {
          xmitter.passphrase = pass.getBytes();
          xmitter.passLen = pass.length();
        }

        xmitter.mac = new char[6];
        xmitter.preamble = new char[6];
        String[] macParts = wifiInf.getBSSID().split(":");

        xmitter.preamble[0] = 0x45;
        xmitter.preamble[1] = 0x5a;
        xmitter.preamble[2] = 0x50;
        xmitter.preamble[3] = 0x52;
        xmitter.preamble[4] = 0x32;
        xmitter.preamble[5] = 0x32;

        for (int i = 0; i < 6; i++)
          xmitter.mac[i] = (char) Integer.parseInt(macParts[i], 16);
        xmitter.resetStateMachine();
        xmitter.execute("");
      } else {
        xmitStarted = false;
        xmitter.cancel(true);
      }
    } catch (Error err) {
      Log.e("MRVL", err.toString());
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }


  private String[] strWavs;
  private int index = 0;

  private void connectByAudio() {
    Task.call(new Callable<JSONObject>() {
      @Override
      public JSONObject call() throws Exception {//这里可以返回空值，把返回类型设为Void即可,返回其他类型的用法将在下面提到
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        long sec = (System.currentTimeMillis()/1000);
        param_.put("appid", "xiaoxiaoban");
        param_.put("timestamp", sec);
        param_.put("signature", Tools.Encrypt("xiaoxiaoban" + sec +  "xxb_4469fe575896cb15", "")); // (appid+timestamp+app_secret)
        param_.put("ssid", mSSID);

        if (Tools.isNotEmpty(input_password.getText().toString()))
          param_.put("password", input_password.getText().toString().trim());

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        param_.put("extra", lu.id);

        return HttpUtils.startRequestJsonObj("http://conn.dandanman.com/api/app_request_wav_ex", param_,
                HttpUtils.TAG_POST_REQUEST);
      }
    }, Task.BACKGROUND_EXECUTOR).onSuccess(new Continuation<JSONObject, Object>() {

      @Override
      public Void then(Task<JSONObject> task) throws Exception {
        if (task.getResult() != null) {
          int ret = task.getResult().getInt("err");
          /**
           *   1: 参数错误
           2: 生成声波失败
           3: 签名验证失败
           4: 时间戳错误
           */
          switch (ret) {  //
            case 0:

              JSONArray array =  task.getResult().getJSONArray("wavs");
              // strWavs = array.toString().split(",");

              List<String> list = new ArrayList<String>();
              for (int i=0; i<array.length(); i++) {
                list.add( array.getString(i) );
              }
              strWavs = list.toArray(new String[list.size()]);

              playSound();
              break;
            case 1:
              toastShow("参数错误");
              break;
            case 2:
              toastShow("生成声波失败");
              break;
            case 3:
              toastShow("签名验证失败");
              break;
            case 4:
              toastShow("时间戳错误");
              break;
          }
        }

//        toWifiHotSpotListActivity();

        return null;
      }
    }, Task.UI_THREAD_EXECUTOR);//主线程运行
  }

  private MediaPlayer mediaPlayer = new MediaPlayer();

  private void playSound() {
    if (mediaPlayer != null) {
      mediaPlayer.stop();
      mediaPlayer.release();
      mediaPlayer = null;
    }

    if (strWavs != null) {
      if (mediaPlayer == null)
        mediaPlayer = new MediaPlayer();
      try {
        mediaPlayer.setDataSource(strWavs[index]);
      } catch (IOException e) {
        e.printStackTrace();
      }
      mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
          mediaPlayer.start();
        }
      });
      mediaPlayer.prepareAsync();

      mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
          nextplay();
        }
      });
    }
  }


  private void playindex(int idx) {
    if (mediaPlayer != null) {
      mediaPlayer.stop();
      mediaPlayer.release();
      mediaPlayer = null;
    }
    mediaPlayer = new MediaPlayer();
    try {
      mediaPlayer.setDataSource(strWavs[index]);
    } catch (IOException e) {
      e.printStackTrace();
    }
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
      @Override
      public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();
      }
    });
    mediaPlayer.prepareAsync();

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
      @Override
      public void onCompletion(MediaPlayer mp) {
        nextplay();
      }
    });
  }

  public void nextplay(){
    ++index;
    if (index >= strWavs.length) {
      index = 0;
    }
    playindex(index);
  }

//  private int markerVer = 2; // 默认低配

  /*
   * (non-Javadoc)
   *
   * @see android.view.View.OnClickListener#onClick(android.view.View)
   */
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.synchronize_wifi_btn:

        if (Tools.isEmpty(input_wifiname.getText().toString().replaceAll(" ", ""))) {
          toastShow("请填写wifi名称");
          return;
        } else {
          showTipDialog();

          if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler.postDelayed(new Runnable() {
              @Override
              public void run() {
                showErrTipDialog();
              }
            }, 1000*120);
          }

          connectByAudio();

          mhandler2.postDelayed(new Runnable() {
            @Override
            public void run() {
              toWifiHotSpotListActivity();
            }
          }, 60*1000);
          //toWifiHotSpotListActivity();

          mhandler.removeCallbacksAndMessages(null);
          mhandler.postDelayed(new Runnable() {
            @Override
            public void run() {
              checkIfBindSuccess();
            }
          }, 6000);
        }
        break;
      default:
        break;
    }
  }
}
